class PostsController < ApplicationController
  caches_page :show
  cache_sweeper :record_sweeper, :only => [:create, :update, :destroy]
  before_filter :require_admin, :except => [:show, :list]
  before_filter :find_or_initialize_friend_post,:except => [:index, :create]
  #  after_filter :expire_fragment_cache, :only => [:create,:update,:destroy]
  # GET /posts
  # GET /posts.xml

  def list
    @posts = Post.all(:page => params[:page])

    respond_to do |format|
      format.html { render :layout => 'application'}
      format.xml  { render :xml => @posts }
    end
  end

  def index
    @posts = @current_user.posts

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
    end
  end

  # GET /posts/1
  # GET /posts/1.xml
  def show
    Post.increase_view_count(params[:id]) # 增加浏览次数
    @post = Post.find(params[:id])
    @title = "#{@post.title} - #{@post.category_name}"
    @description = @post.title
    respond_to do |format|
      format.html { render :layout => 'application'}# show.html.erb
      format.xml  { render :xml => @post }
    end
  end

  # GET /posts/new
  # GET /posts/new.xml
  def new
    @post = Post.new
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @post }
    end
  end


  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

  # POST /posts
  # POST /posts.xml
  def create
    @post = @current_user.posts.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to(@post, :notice => '日志生成成功!') }
        format.xml  { render :xml => @post, :status => :created, :location => @post }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /posts/1
  # PUT /posts/1.xml
  def update
    @post = Post.find(params[:id])

    respond_to do |format|
      if @post.update_attributes(params[:post])
        format.html { redirect_to(@post, :notice => '日志更新成功!') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.xml
  def destroy
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to(root_url) }
      format.xml  { head :ok }
    end
  end

  private
  def find_or_initialize_friend_post
    @post = params[:id] ? Post.find(params[:id]) : Post.new
  end
  
  # => 清除右侧目录树片段的缓存
  def expire_fragment_cache
    expire_fragment(RecordSweeper::PATH.merge(:action_suffix => 'archive_tree'))
  end
end
